<template>
  <view class="viewport" id="viewport">
    <view
      class="header1"
      id="header1"
      :style="{ paddingTop: safeAreaInsets.windowTop + 'px' }"
      v-if="!isSticky"
    >
      <view class="left icon-left" @tap="Onleft()"></view>
      <uni-title type="h1" align="center" title="随心记" class="text"></uni-title>
      <view
        v-if="query.ID != -1 || memberStore.profile?.UserName == '哥哥'"
        class="btn right"
        @tap="submit"
        >提交</view
      >
      <view v-if="query.ID != -1" class="btn left1" @tap="del">删除</view>
    </view>
    <view id="input" v-if="!isSticky">
      <view class="noteTypeGroup">
        <input class="uni-input notetype" v-model="noteType" placeholder="请输入类别" />
        <view class="condition">
          <picker @change="pickerNoteTypeChange" mode="selector" :range="noteTypes">
            <text class="account">{{ curNoteType }}</text></picker
          >
        </view>
      </view>
      <input class="uni-input" v-model="title" placeholder="请输入标题" />
      <uni-data-checkbox class="chk" v-model="isColl" :localdata="checkdata" mode="default" />
    </view>
    <editor
      id="editor"
      ref="container"
      class="edit"
      :class="{ editTop: isSticky }"
      placeholder="开始输入..."
      show-img-size
      show-img-toolbar
      show-img-resize
      @statuschange="onStatusChange"
      :read-only="readOnly"
      @ready="onEditorReady"
      @input="getData"
      @focus="setFixed(true)"
      @blur="setFixed(false)"
    >
    </editor>
  </view>
  <view
    class="toolbar fixed"
    id="toolbar"
    @touchend.prevent="format"
    v-if="isSticky"
    :style="{ top: windowHeightOrgin - windowHeightCur + 'px' }"
  >
    <view :class="formats.bold ? 'ql-active' : ''" class="iconfont icon-zitijiacu" data-name="bold">
    </view>
    <view
      :class="formats.italic ? 'ql-active' : ''"
      class="iconfont icon-zitixieti"
      data-name="italic"
    >
    </view>
    <view
      :class="formats.underline ? 'ql-active' : ''"
      class="iconfont icon-zitixiahuaxian"
      data-name="underline"
    ></view>
    <view
      :class="formats.strike ? 'ql-active' : ''"
      class="iconfont icon-zitishanchuxian"
      data-name="strike"
    ></view>
    <!-- #ifndef MP-BAIDU -->
    <view
      :class="formats.align === 'left' ? 'ql-active' : ''"
      class="iconfont icon-zuoduiqi"
      data-name="align"
      data-value="left"
    ></view>
    <!-- #endif -->
    <view
      :class="formats.align === 'center' ? 'ql-active' : ''"
      class="iconfont icon-juzhongduiqi"
      data-name="align"
      data-value="center"
    ></view>
    <!-- #ifndef MP-BAIDU -->
    <view
      :class="formats.lineHeight ? 'ql-active' : ''"
      class="iconfont icon-line-height"
      data-name="lineHeight"
      data-value="2"
    ></view>
    <view
      :class="formats.letterSpacing ? 'ql-active' : ''"
      class="iconfont icon-Character-Spacing"
      data-name="letterSpacing"
      data-value="2em"
    ></view>
    <view
      :class="formats.marginTop ? 'ql-active' : ''"
      class="iconfont icon-722bianjiqi_duanqianju"
      data-name="marginTop"
      data-value="20px"
    ></view>
    <view
      :class="formats.marginBottom ? 'ql-active' : ''"
      class="iconfont icon-723bianjiqi_duanhouju"
      data-name="marginBottom"
      data-value="20px"
    ></view>
    <!-- #endif -->

    <view class="iconfont icon-clearedformat" @touchend.prevent="removeFormat"></view>

    <!-- #ifndef MP-BAIDU -->
    <view
      :class="formats.fontFamily ? 'ql-active' : ''"
      class="iconfont icon-font"
      data-name="fontFamily"
      data-value="Pacifico"
    ></view>
    <view
      :class="formats.fontSize === '24px' ? 'ql-active' : ''"
      class="iconfont icon-fontsize"
      data-name="fontSize"
      data-value="24px"
    ></view>
    <!-- #endif -->
    <view
      :class="formats.color === '#0000ff' ? 'ql-active' : ''"
      class="iconfont icon-text_color"
      data-name="color"
      data-value="#0000ff"
    ></view>
    <view
      :class="formats.backgroundColor === '#00ff00' ? 'ql-active' : ''"
      class="iconfont icon-fontbgcolor"
      data-name="backgroundColor"
      data-value="#00ff00"
    ></view>
    <view class="iconfont icon--checklist" data-name="list" data-value="check"></view>
    <view
      :class="formats.list === 'ordered' ? 'ql-active' : ''"
      class="iconfont icon-youxupailie"
      data-name="list"
      data-value="ordered"
    ></view>
    <view
      :class="formats.list === 'bullet' ? 'ql-active' : ''"
      class="iconfont icon-wuxupailie"
      data-name="list"
      data-value="bullet"
    ></view>

    <view class="iconfont icon-undo" @touchend.prevent="undo"></view>
    <view class="iconfont icon-redo" @touchend.prevent="redo"></view>

    <view class="iconfont icon-outdent" data-name="indent" data-value="-1"></view>
    <view class="iconfont icon-indent" data-name="indent" data-value="+1"></view>
    <view class="iconfont icon-fengexian" @touchend.prevent="insertDivider"></view>
    <view
      :class="formats.header === 2 ? 'ql-active' : ''"
      class="iconfont icon-format-header-2"
      data-name="header"
      :data-value="2"
    ></view>
    <view class="iconfont icon-shanchu" @touchend.prevent="clear"></view>
    <view class="iconfont icon-date" @touchend.prevent="insertDate"></view>
  </view>
</template>
<script setup lang="ts">
import { GetNoteTypeAPI } from '@/services/detail'
import { AddOrUpdate, Del, NoteIndex } from '@/services/notelog'
import { useMemberStore } from '@/stores'
import { onLoad, onPageScroll } from '@dcloudio/uni-app'
import { onMounted, ref } from 'vue'
const isSticky = ref(false)
const safeAreaInsets = uni.getSystemInfoSync()
const readOnly = false
const result = ref('')
const noteType = ref('')
const isColl = ref(false)
const formats = ref({})
const scrollTop = ref(0)
const windowHeightOrgin = ref(0)
const windowHeightCur = ref(0)
const initHeight = 0
const toolbarID = 0
const NewID = ref(0)
const noteTypes = ref<string[]>()
const curNoteType = ref<string>('请选择')
const title = ref('')
const editorHeight = ref(400)
const editorCtx = ref<UniHelper.Editor>()
// 获取会员信息
const memberStore = useMemberStore()
// 定义 props 接收
const query = defineProps<{
  ID: number
  UserTitle: string
}>()
const checkdata = [
  { value: true, text: '置顶' },
  { value: false, text: '不置顶' },
]
//初始化账户类型列表
const InitNoteType = async () => {
  if (memberStore.profile) {
    const res = await GetNoteTypeAPI({
      Auth: memberStore.profile.Token,
      UserGroup: memberStore.profile.UserGroup,
    })
    res.result.push('请选择')
    noteTypes.value = res.result
  }
}
//加载初始化
onLoad(async () => {
  await InitNoteType()
  if (query.ID) {
    const res = await NoteIndex({
      Auth: memberStore.profile!.Token,
      UserName: '',
      ID: query.ID,
      UserTitle: '',
      NoteType: '',
      UserGroup: memberStore.profile!.UserGroup,
    })
    var one = res.result[0]
    title.value = one.UserTitle
    result.value = one.UserContent
    isColl.value = one.IsColl
    noteType.value = one.NoteType
    NewID.value = one.ID
    editorCtx.value?.setContents({
      html: result.value, //this.EditGoodsDetail.content为赋值内容。
    })
  }
  windowHeightOrgin.value = uni.getSystemInfoSync().windowHeight
  windowHeightCur.value = uni.getSystemInfoSync().windowHeight
  if (query.UserTitle) {
    title.value = query.UserTitle
  }
})
onPageScroll(async () => {
  //nvue暂不支持滚动监听，可用bindingx代替
  updateWindowHeight()
})
//选择账户类型
const pickerNoteTypeChange = async (e: any) => {
  const index = e.detail.value as number
  curNoteType.value = noteTypes.value![index]
  if (curNoteType.value != '请选择') noteType.value = noteTypes.value![index]
}
const keyboardHeightChange = (event: any) => {
  // 获取键盘高度
  const keyboardHeight = event.detail.height
  scrollTop.value = keyboardHeight
  // // 调整固定元素的样式，使其与键盘高度保持一致
  // toolbar.style.bottom = keyboardHeight + 'px'
  // editor.style.bottom = keyboardHeight + 'px'
}
const keyboardComplete = () => {
  // 键盘打开或关闭完成后的处理逻辑
  // 恢复固定元素的样式
  // toolbar.style.bottom = '0'
  // editor.style.bottom = '0'
}
const setFixed = (status: boolean) => {
  isSticky.value = status
  windowHeightCur.value = uni.getSystemInfoSync().windowHeight
}
const setEditorHeight = () => {
  isSticky.value = true
  // var body = document.querySelector('#viewport')!.clientHeight
  // var win =    uni.getWindowInfo().windowHeight
  // if(win<body){
  //   editorHeight.value =body-win
  // }else{
  // editorHeight.value =
  //   uni.getWindowInfo().windowHeight - document.querySelector('#toolbar')?.clientTop!- document.querySelector('#toolbar')!.clientHeight- document.querySelector('#toolbar')!.clientHeight
  // }
}
const handleScroll = async (event: any) => {
  console.log('123456')
  scrollTop.value = event.detail.scrollTop
}
const submit = async () => {
  if (memberStore.profile) {
    await AddOrUpdate({
      Auth: memberStore.profile.Token,
      ID: NewID.value,
      UserName: memberStore.profile.UserName,
      IsColl: isColl.value,
      UserTitle: title.value,
      UserContent: result.value,
      NoteType: noteType.value,
      UserGroup: memberStore.profile.UserGroup,
    })
    uni.showToast({ icon: 'success', title: '提交成功' })
    setTimeout(() => {
      // 页面跳转
      Onleft()
    }, 500)
  }
}
const del = async () => {
  if (memberStore.profile) {
    await Del({
      Auth: memberStore.profile.Token,
      ID: NewID.value,
    })
    uni.showToast({ icon: 'success', title: '删除成功' })
    setTimeout(() => {
      // 页面跳转
      Onleft()
    }, 500)
  }
}

const getData = (e: any) => {
  result.value = e.detail.html
  windowHeightCur.value = uni.getSystemInfoSync().windowHeight
}
const updateWindowHeight = () => {
  windowHeightCur.value = uni.getSystemInfoSync().windowHeight
}
const onEditorReady = () => {
  // #ifdef MP-BAIDU
  editorCtx.value = requireDynamicLib('editorLib').createEditorContext('editor')
  // #endif

  // #ifdef APP-PLUS || MP-WEIXIN || H5
  uni
    .createSelectorQuery()
    .select('#editor')
    .context((res: any) => {
      editorCtx.value = res.context
    })
    .exec()

  // #endif
}
const undo = () => {
  editorCtx.value?.undo()
}
const redo = () => {
  editorCtx.value?.redo()
}
const format = (e: any) => {
  let { name, value } = e.target.dataset
  if (!name) return
  editorCtx.value?.format(name, value)
}
const onStatusChange = (e: any) => {
  formats.value = e.detail
}
//返回
const Onleft = () => {
  uni.navigateTo({ url: '/pages/NoteAcount/NoteLogMain' })
  // uni.navigateBack({
  //   delta: 1,
  // })
}
const insertDivider = () => {
  editorCtx.value?.insertDivider({
    success: function () {
      console.log('insert divider success')
    },
  })
}
const clear = () => {
  uni.showModal({
    title: '清空编辑器',
    content: '确定清空编辑器全部内容？',
    success: (res) => {
      if (res.confirm) {
        editorCtx.value?.clear()
      }
    },
  })
}
const removeFormat = () => {
  editorCtx.value?.removeFormat()
}
const insertDate = () => {
  const date = new Date()
  const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
  editorCtx.value?.insertText({
    text: formatDate,
  })
}
const insertImage = () => {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      editorCtx.value?.insertImage({
        src: res.tempFilePaths[0],
        alt: '图像',
        success: function () {
          console.log('insert image success')
        },
      })
    },
  })
}

function mounted() {
  throw new Error('Function not implemented.')
}
</script>

<style lang="scss">
@import './styles/editor-icon.css';
@import './styles/NoteLog.scss';
</style>
